/*
 * Copyright：fxsen <br/>
 * Date: 2021/12/9 19:28 <br/>
 * Author: <a href="mailto:fxsen@foxmail.com">fxsen</a>
 */
package com.fxsen.platform.web.controllers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fxsen.commons.core.annotation.RecordLog;
import com.fxsen.commons.core.annotation.RequiredPermission;
import com.fxsen.commons.core.base.result.ResponseResult;
import com.fxsen.commons.core.base.result.ResultJson;
import com.fxsen.commons.core.constant.Constants;
import com.fxsen.commons.utils.Md5Utils;
import com.fxsen.commons.sysmanager.core.entity.User;
import com.fxsen.commons.sysmanager.core.entity.query.UserQuery;
import com.fxsen.commons.sysmanager.core.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @describe: 系统用户控制层 <br/>
 * @date: 2021/12/9 19:28 <br/>
 * @author: <a href="mailto:fxsen@foxmail.com">fxsen</a>
 */
@RestController
@RequestMapping("user")
@RequiredPermission("user")
@Api(tags = "系统：用户接口")
public class UserController  {
    /**
     * 服务对象
     */
    @Autowired
    private IUserService userService;
    /**
    * 获取分页列表
    * @param page 页码
    * @param limit 条数
    * @param query 查询对象
    * @return {@link ResultJson} 返回对象
    * @date 2021/12/12 18:50
    * @author <a href="mailto:fxsen@foxmail.com">fxsen</a> <br/>
    * @version 1.0.0 <br/>
    **/
    @ApiOperation(value = "列表")
    @GetMapping("list")
    @RequiredPermission("user:list")
    public ResponseResult page(@RequestParam(value = "page",required = false,defaultValue = "1") int page,
                               @RequestParam(value = "limit",required = false,defaultValue = "10") int limit, UserQuery query, HttpServletRequest request){
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            if (null != query){
                if (StringUtils.isNotBlank(query.getLoginName())){
                    queryWrapper.like("login_name",query.getLoginName());
                }
                if (StringUtils.isNotBlank(query.getUserName())){
                    queryWrapper.like("user_name",query.getUserName());
                }
                if (null != query.getSex()){
                    queryWrapper.eq("sex",query.getSex());
                }
                if (StringUtils.isNotBlank(query.getType())){
                    queryWrapper.eq("type",query.getType());
                }
            }
            Page<User> userPage = userService.page(new Page<>(page,limit), queryWrapper);
            return ResponseResult.success(userPage);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "保存")
    @PostMapping("save")
    @RecordLog("新增用户")
    @RequiredPermission("user:save")
    public ResponseResult save(@RequestBody User user){
        try {
            if (null == user){
                return ResponseResult.failed("未传请求参数！");
            }
            String password = user.getPassword();
            String loginName = user.getLoginName();
            if (StringUtils.isBlank(loginName)){
                return ResponseResult.failed("账号不能为空！");
            }
            String userName = user.getUserName();
            if (StringUtils.isBlank(userName)){
                return ResponseResult.failed("用户名不能为空！");
            }
            String phone = user.getPhone();
            if (StringUtils.isBlank(phone)){
                return ResponseResult.failed("手机号不能为空！");
            }
            if (userService.isExist("login_name",loginName)){
                return ResponseResult.failed("账号“"+loginName+"”已存在！");
            }
            if (userService.isExist("user_name",userName)){
                return ResponseResult.failed("用户名“"+userName+"”已存在！");
            }
            if (userService.isExist("phone",phone)){
                return ResponseResult.failed("手机号“"+phone +"”已存在！");
            }
            if (StringUtils.isBlank(password)){
                password = Constants.DEFAULT_PASSWORD;
            }
            user.setPassword(Md5Utils.digest(password));
            boolean save = userService.save(user);
            return save ? ResponseResult.success() : ResponseResult.saveFailed();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "修改")
    @PostMapping("update")
    @RecordLog("更新用户")
    @RequiredPermission("user:update")
    public ResponseResult update(@RequestBody User user){
        try {
            if (null == user || StringUtils.isBlank(user.getId())){
                return ResponseResult.failed("未传请求参数！");
            }
            String userId = user.getId();
            String password = user.getPassword();
            String loginName = user.getLoginName();
            if (StringUtils.isBlank(loginName)){
                return ResponseResult.failed("账号不能为空！");
            }
            String userName = user.getUserName();
            if (StringUtils.isBlank(userName)){
                return ResponseResult.failed("用户名不能为空！");
            }
            String phone = user.getPhone();
            if (StringUtils.isBlank(phone)){
                return ResponseResult.failed("手机号不能为空！");
            }
            User byId = userService.getById(userId);
            if (!byId.getLoginName().equals(loginName) && userService.isExist("login_name",loginName)){
                return ResponseResult.failed("账号“"+loginName+"”已存在！");
            }
            if (!byId.getUserName().equals(userName) && userService.isExist("user_name",userName)){
                return ResponseResult.failed("用户名“"+userName+"”已存在！");
            }
            if (!byId.getPhone().equals(phone) && userService.isExist("phone",phone)){
                return ResponseResult.failed("手机号“"+phone +"”已存在！");
            }
            if (StringUtils.isBlank(password)){
                password = Constants.DEFAULT_PASSWORD;
            }
            user.setPassword(Md5Utils.digest(password));
            boolean save = userService.save(user);
            return save ? ResponseResult.success() : ResponseResult.saveFailed();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "删除")
    @GetMapping("delete")
    @RecordLog("删除用户")
    @RequiredPermission("user:delete")
    public ResponseResult delete(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response){
        try {
            if (StringUtils.isBlank(id)) return ResponseResult.failed("未传请求参数！");
            User user = userService.getById(id);
            if (user.getLoginName().equals("admin")){
                return ResponseResult.failed("该账号禁止删除~");
            }
            boolean remove = userService.removeById(id);
            return remove ? ResponseResult.success() : ResponseResult.deleteFailed();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    /**
    * 主键获取
    * @param id 主键id
    * @return {@link ResultJson}
    * @date 2021/12/13 19:37
    * @author <a href="mailto:fxsen@foxmail.com">付强</a> <br/>
    * @version 1.0.0 <br/>
    **/
    @ApiOperation(value = "获取一条")
    @GetMapping("getOne")
    public ResponseResult getOne(@RequestParam("id") String id){
        try {
            if (StringUtils.isBlank(id)) return ResponseResult.failed("未传请求参数！");
            return ResponseResult.success(userService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
}



